package com.briup.common.config;

import com.briup.common.properties.ZookeeperProperties;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author wood
 */
@ConditionalOnProperty("briup.config.zookeeper.address")
@Configuration
public class ZookeeperAutoConfig {

    @Autowired
    private ZookeeperProperties zookeeperProperties;


    @Bean
    public CuratorFramework curatorFramework(){
        CuratorFramework client = null;

        // 重试策略
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(zookeeperProperties.getBaseSleepTimeMs(),zookeeperProperties.getMaxRetries());


        // 创建CuratorFramework
        client = CuratorFrameworkFactory.builder()
                .connectString(zookeeperProperties.getAddress())
                .sessionTimeoutMs(zookeeperProperties.getSessionTimeoutMs())
                .connectionTimeoutMs(zookeeperProperties.getConnectionTimeoutMs())
                .retryPolicy(retryPolicy)
                .build();

        // 开启连接
        client.start();

        return client;
    }


}
